#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "cappacket.h"
#include "mainwindow.h"
#include <cmath>
#include <QDebug>
#include <QMessageBox>
#define PI 3.1415927

QString etherPortName;

void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
CapPacket::CapPacket()
{

    m_isOK=false;
    m_iStartPoint = 0;
    m_dblSin = 0;		// 实部
    m_dblCos = 0;		// 虚部
    m_iZhouQiShu = 1;	// 采样周期数
    m_dblYouXiaoZhi = 0;	// 互感器有效值
    m_dblXW = 0;			// 互感器所示相位
    m_dblFuZhi = 11585;		// 幅值
    m_iLastSmpcnt = -1;		// 最后一个SmpCnt值
    m_iPoints = 0;			// 计算公式所包含点数
    myDB=new ProjectDB();
    m_bInitCapPara=false;
    m_iJs=0;
    m_iLost=0;
    m_bBegin=false;
    jsFlag=-1;
 //   memset(m_szl,0,sizeof(m_szl));
    iSuanFa=0;
    testType=0;
    dblMaxJg=0;
    dblMinJg=1000;
    testSelect=0;
    xieboNum=0;

    harmonicOrder = 1;
}
void CapPacket::init()
{
    memset(m_PointArray,0,sizeof(m_PointArray));
    m_iShuZiLiangMax=0;
    m_iShuZiLiangMax_Temp=0;
}

void CapPacket::run()
{
    m_bBegin=false;
    maxSmpCnt=0;
    m_iLost=0;
    jsFlag=-1;
    getSysLoad();
    dblMaxJg=0;
    dblMinJg=1000;
    memset(t_MAC,0,sizeof(t_MAC));
    memset(t_cypl,0,sizeof(t_cypl));
    MuNum=0;
    m_bCapIsNoError=true;
    m_iTongDaoReal=-1;
    while(m_bInitCapPara)//LM:修改网口标志
    {

        if(m_bStopCap)
            break;
        if (testType==1)
            FindAll();
        else if (testType==2)
            myLubo();
        else if (testType=='S')
            showAll();
        else            
            CapNextPkt();
    }
}
void CapPacket::getSysLoad()
{
    QSqlQuery tbmu;
    tbmu=myDB->openWcxxforSql("select * from muinfo");
    if (tbmu.next())
    {
        APPID=tbmu.value(0).toString();
        MAC=tbmu.value(1).toString();
        CYPL=tbmu.value(2).toInt();
    }
    else
    {
        APPID="";
        MAC="";
        CYPL=4000;
    }
    tbmu.clear();
}

// 设置抓包和处理数据的参数
bool CapPacket::SetCapParamater(int iTongDao, int iZhouQi, int iSmpCntStart, double dblFuZhi)
{
    m_iZhouQiShu = iZhouQi;	// 采样周期数
    m_dblFuZhi = dblFuZhi;		// 幅值
        m_iTongDao = iTongDao;
        m_iZhouQi = iZhouQi;
/*
        m_PointArray=(double **)malloc(sizeof(double)*m_iTongDaoCount);
        for(int i=0;i<m_iTongDaoCount;i++)
        {
            m_PointArray[i]=(double *)malloc((sizeof(double))*(m_iZhouQi * m_iSmpRate));
        }
*/
//        if(iTongDao == TestChannel_LuBo)
//        {
//            memset()
//        }
        memset(m_PointArray,0,sizeof(m_PointArray));
        memset(m_tempArray,0,sizeof(m_tempArray));

        m_iShuZiLiangMax = 0;
        m_iShuZiLiangMax_Temp = 0;
        m_iStartPoint = iSmpCntStart;
        m_iTestedPoints = 0;
        m_bSamplingPoints = false;
      //  m_CurrentAPDU = 0;
        m_bStopCap = false;
        m_dblFuZhi = dblFuZhi;
        return true;
}

void CapPacket::freeData()
{
    for(int i=0;i<m_iTongDaoCount;i++)
        free(m_PointArray[i]);
    free(m_PointArray);
  //  delete[] m_SmpCntArray;

/*
    for   (int i=0;i<m_iZhouQi * m_iSmpRate;i++)
    {
        delete [] m_PointArray[i];//由里至外，进行释放内存。
        m_PointArray[i]=NULL;//不要忘记，释放空间后p[i]不会自动指向NULL值，还将守在原处，只是释放内存而已，仅此而已。
    }
    delete   []m_PointArray;
    m_PointArray   =   NULL;
*/
}

// 关闭网口
bool CapPacket::Close(void)
{

    //pcap_close(m_fp);
    //关闭网口
    m_bInitCapPara = false;
    m_bBegin=false;
    return true;

}
bool CapPacket::Open(int flag)
{
        if (flag==1)
            getSysLoad();
        char errbuf[PCAP_ERRBUF_SIZE];		// 错误缓冲区
    //    pcap_if_t *alldevs;		// 可用设备列表
        struct pcap_pkthdr *header;
        const u_char *pkt_data;
        int res;
        /*
        //判断是否存在可用通道        
        if (pcap_findalldevs(&alldevs, errbuf) == -1)
                return false;
        pcap_if_t *d;
        d = alldevs;
        if(d == NULL)
        {
                m_sAnalyseResult = "找不到指定设备！";
                m_bInitCapPara = false;
                return m_bInitCapPara;
        }
        */
        m_bInitCapPara = true;

        //========================================================================
        // 打开端口
//        QString sNetPortDescription=NETDEV;
//        QByteArray ba=sNetPortDescription.toLatin1();
//        char *dev=ba.data();
    //    pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);
   //     if ((m_fp = pcap_open_live(dev,65535,0,500,errbuf)) == NULL)
        if ((m_fp = pcap_open_live(etherPortName.toLatin1().data(),BUFSIZ,1,10,errbuf)) == NULL)
        {
                m_sAnalyseResult = "端口打开失败！";
                m_bInitCapPara = false;
                return m_bInitCapPara;
        }
                // ==========================================================================
        /*设置为非阻塞状态
        if(pcap_setnonblock(m_fp,0,errbuf)<0)
        {
            m_bInitCapPara = false;
            return m_bInitCapPara;
        }
        */

                // 捕获一个数据包
        int izbnum=0;
        while(m_bInitCapPara)//LM
        {
            if(m_bStopCap)
            {
                m_bInitCapPara=false;
                return m_bInitCapPara;
                break;
            }
            res = pcap_next_ex(m_fp, &header, &pkt_data);
            izbnum++;
            if (izbnum>120)
                return m_bInitCapPara;
            if ((res< 1)||(header->len < 30))
            {
                m_bInitCapPara = false;
                m_sAnalyseResult = "端口打开失败！";
                m_bInitCapPara=false;
                //    return m_bInitCapPara;
            }
            else
            {
                unsigned int i, j;
                bool IsYiTaiWang;
                int ethType;//0:sv;1:goose;
                IsYiTaiWang = false;
                ethType=0;
                for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
                {
                        //=======================================================
                        // 以太网标志
                        if (pkt_data[i] == 0x88 && ((pkt_data[i + 1] == 0xba) ||(pkt_data[i + 1] == 0xb8)))
                        {
                                if(i > 11)
                                {
                                        IsYiTaiWang = true;
                                        if (pkt_data[i + 1] == 0xb8)
                                            ethType=1;
                                        QString sDestination = "目的地址：", sSource = "  源 地 址：";
                                        for(j = 0; j < 6; j++)
                                        {
                                                sDestination += getHexFormat(pkt_data[j]) + " ";
                                                sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                        }
                                        m_sAnalyseResult = sDestination;
                                        m_sAnalyseResult += sSource;
                                        QString sTPID = "\nTPID：", sTCI = "  TCI：";
                                        if(i >= 14) sTPID += getHexFormat(pkt_data[12]) + " " + getHexFormat(pkt_data[13]);
                                        if(i >= 16)	sTCI += getHexFormat(pkt_data[14]) + " " + getHexFormat(pkt_data[15]);
                                        m_sAnalyseResult += sTPID;
                                        m_sAnalyseResult += sTCI;
                                        break;
                                }else
                                {
                                        if(i < 11) continue;
                                }
                        }
                }
                if(IsYiTaiWang)
                {
                    QString tempAPPID=getHexFormat(pkt_data[i + 2])+getHexFormat(pkt_data[i+3]);
                    QString ma=getHexFormat(pkt_data[0]) +"-";
                    ma +=getHexFormat(pkt_data[1]) +"-";
                    ma +=getHexFormat(pkt_data[2]) +"-";
                    ma +=getHexFormat(pkt_data[3]) +"-";
                    ma +=getHexFormat(pkt_data[4]) +"-";
                    ma +=getHexFormat(pkt_data[5]);
               //     qDebug()<<ma <<" "<<tempAPPID;
                    QString  sTemp;
                    if (ethType==0)
                        m_sAnalyseResult += "\n以太网类：88 ba";
                    else if (ethType==1)
                        m_sAnalyseResult += "\n以太网类：88 b8";
                  //  QString tempAPPID=getHexFormat(pkt_data[i + 2]) +getHexFormat(pkt_data[i + 3]);
                    if (flag==1)
                        if((APPID!=tempAPPID)||(MAC!=ma))
                            return true;

                            sTemp = "  APPID：" + getHexFormat(pkt_data[i + 2]) + " " + getHexFormat(pkt_data[i + 3]);
                            m_sAnalyseResult += sTemp;
                            sTemp = "  LENGTH：";
                            int iLength = (pkt_data[i + 4] << 8) + pkt_data[i + 5];
                            sTemp += QString::number(iLength,16);
                            m_sAnalyseResult += sTemp;
                            sTemp = "\n保留1：" + getHexFormat(pkt_data[i + 6]) + " " + getHexFormat(pkt_data[i + 7]);
                            m_sAnalyseResult += sTemp;
                            sTemp = "  保留2：" + getHexFormat(pkt_data[i + 8]) + " " + getHexFormat(pkt_data[i + 9]);
                            m_sAnalyseResult +=  sTemp;
                            if (pkt_data[i + 10] == 0x80)
                            {
                                m_sAnalyseResult +=  "\nTag：80";
                                m_iAPDU_Start = i + 10;
                                SetCapPara_91(pkt_data, header->len);
                            }
                            else if(pkt_data[i + 10] == 0x60)
                            {
                                m_sAnalyseResult +=  "\nTag：60";
                                m_iAPDU_Start = i + 10;
                                SetCapPara_92(pkt_data, header->len);
                            }
                            else
                            {
                                m_sAnalyseResult +=  "\n非9-1或9-2数据！";
                                m_bInitCapPara = false;
                            }
                            m_bInitCapPara=true;
                            setJqxs();          //可去除
                            return m_bInitCapPara;
                }
                else            //IsYiTaiWang
                {
                    m_bInitCapPara = false;
                    m_sAnalyseResult = "非以太网数据！";
                    m_sGuiYueType = NotEthernet;
                    m_bInitCapPara=false;
                }
            }

        }

   //     pcap_freealldevs(alldevs);
        return m_bInitCapPara;
}
bool CapPacket::FindAll()
{
        QString m_sAPPID="";
        QString m_sMAC="";
        QString m_sType="";
      //  char errbuf[PCAP_ERRBUF_SIZE];		// 错误缓冲区
      //  pcap_if_t *alldevs;		// 可用设备列表
        struct pcap_pkthdr *header;
        const u_char *pkt_data;
                // 捕获一个数据包

            if(m_bStopCap) return true;		// 外部阻止接口
            int res = pcap_next_ex(m_fp, &header, &pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                m_bInitCapPara = false;
                m_sAnalyseResult = "端口打开失败！";
                m_bInitCapPara=false;
            }
            else
            {
                unsigned int i, j;
                bool IsYiTaiWang;
                int ethType;//0:sv;1:goose;
                IsYiTaiWang = false;
                ethType=0;
                for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
                {
                        if ((pkt_data[i] == 0x88) && (pkt_data[i + 1] == 0xba))
                        {
                                if(i > 11)
                                {
                                        IsYiTaiWang = true;
                                        for(j = 0; j < 6; j++)
                                        {
                                            //    sDestination += getHexFormat(pkt_data[j]) + " ";
                                                m_sMAC +=getHexFormat(pkt_data[j]) +"-";
                                            //    sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                        }
                                        if (m_sMAC.length()>0)
                                            m_sMAC=m_sMAC.left(m_sMAC.length()-1);
                                        break;
                                }else
                                {
                                        if(i < 11) continue;
                                }
                        }
                }
                if(IsYiTaiWang)
                {
                    int iSmpCnt = 0;                // 获取SmpCount值
                    m_sAPPID=getHexFormat(pkt_data[i + 2]) +getHexFormat(pkt_data[i + 3]);
                    if (pkt_data[i + 10] == 0x80)
                    {
                        m_sType="9-1";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_91(pkt_data, header->len);
                    }
                    else if(pkt_data[i + 10] == 0x60)
                    {
                        m_sType="9-2";
                        m_iAPDU_Start = i + 10;
                        SetCapPara_92(pkt_data, header->len);
                    }
                    for(int j = 0; j < m_iASDU_Cnt; j++)
                    {
                        if(m_bStopCap) return true;		// 外部阻止接口
                        int iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                        iSmpCnt = 0;
                        for(int i = 0; i < m_iSmpCnt_Length; i++)
                            iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                        if (maxSmpCnt<iSmpCnt)
                        {
                            maxSmpCnt=iSmpCnt;
                        }
                    }

                    emit sigFind(m_sAPPID,m_sMAC,m_sType,maxSmpCnt,m_iASDU_Cnt);         //显示网络列表
                }
            }
    return true;
}
// 清空缓冲池中的数据
void CapPacket::ClearPksPool(void)
{
        if( m_bInitCapPara )
        {
                struct pcap_pkthdr *header;	// 数据包头
                const u_char *pkt_data;		// 数据包
                int res;
                while((res = pcap_next_ex(m_fp, &header, &pkt_data) > 0))
                {

                }
        }
}

// 获得最大数字量
double CapPacket::getMaxPointValue(void)
{
        int iPoints = m_iZhouQi * m_iSmpRate;
        double dblMaxValue = 0;
        for(int i = 0; i < m_iTongDaoCount; i++)
        {
                if(m_bIsChannelShow[i])
                {
                        for(int j = 0; j < iPoints; j++)
                        {
                                if (std::abs(m_PointArray[i][j]) > dblMaxValue)
                                        dblMaxValue = std::abs(m_PointArray[i][j]);
                        }
                }
        }
        if(dblMaxValue < 1) dblMaxValue = 1;
        return dblMaxValue;
}
// 设置9-1规约的解析包参数
bool CapPacket::SetCapPara_91(const u_char* pkt_data, int pkt_len)
{
    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：9-1\n" + m_sAnalyseResult;
        m_sGuiYueType = GuiYue9_1;
        m_iData_Length = 2;
        m_iTongDao_Length = 2;
        int iLoaction, iBits = 1;	// iBits为长度按ASN.1编码所占字节
        iLoaction = m_iAPDU_Start + 1;
        int iLength = 0;
        if(pkt_data[iLoaction] > 0x80)
        {
                iBits = pkt_data[iLoaction] - 0x80;
                for(int i = 1; i <= iBits; i++)
                        iLength += pkt_data[iLoaction + i] << (8 * (iBits - i));
                iLoaction += iBits;
        }else
                iLength = pkt_data[iLoaction];
        m_sAnalyseResult +=  "\nLength：" + QString::number(iLength,16);
        m_iASDU_Cnt = (pkt_data[iLoaction + 1] << 8) + pkt_data[iLoaction + 2];
        m_sAnalyseResult +=  "\nASDU数目：" + QString::number(m_iASDU_Cnt,16);
        m_iASDU_Length = (pkt_data[iLoaction + 3] << 8) + pkt_data[iLoaction + 4];
        m_sAnalyseResult +=  "  ASDU长度：" + QString::number(m_iASDU_Length,16);
        m_iASDU_Length += 2;
        m_iASDU_Start = iLoaction + 3;
        m_sAnalyseResult +=  "\n逻辑节点名：" + getHexFormat(pkt_data[m_iASDU_Start + 2]);
        m_sAnalyseResult +=  "  数据集名：" + getHexFormat(pkt_data[m_iASDU_Start + 3]);
        m_sAnalyseResult +=  "  逻辑设备名：" + getHexFormat(pkt_data[m_iASDU_Start + 4]);
        m_sAnalyseResult +=" ";
        m_sAnalyseResult += getHexFormat(pkt_data[m_iASDU_Start + 5]);

        m_sAnalyseResult +=  "\n额定相电流：" + getHexFormat((pkt_data[m_iASDU_Start + 6] >> 8)
                        + pkt_data[m_iASDU_Start + 7]);
        m_sAnalyseResult +=  "  额定零序电流：" + getHexFormat((pkt_data[m_iASDU_Start + 8] >> 8)
                        + pkt_data[m_iASDU_Start + 9]);
        m_sAnalyseResult +=  "  额定相电压：" + getHexFormat((pkt_data[m_iASDU_Start + 10] >> 8)
                        + pkt_data[m_iASDU_Start + 11]);
        m_sAnalyseResult +=  "\n额定延迟时间：" + getHexFormat((pkt_data[m_iASDU_Start + 12] >> 8)
                        + pkt_data[m_iASDU_Start + 13]);
        m_iSync_Start = 0; //9-1没有同步标志位， 所以置0
        m_iFirstData_Start = m_iASDU_Start + 14 ;
        m_iFirstSmpCnt_Start = m_iASDU_Start + 42;
        m_iSmpCnt_Length = 2;
        m_sAnalyseResult += "\n状态字1：" + getHexFormat(pkt_data[m_iASDU_Start + 38]) + " "
                        + getHexFormat(pkt_data[m_iASDU_Start + 39]);
        m_sAnalyseResult +=  "  状态字2：" + getHexFormat(pkt_data[m_iASDU_Start + 40]) + " "
                        + getHexFormat(pkt_data[m_iASDU_Start + 41]);
        m_iSmpRate = pkt_data[m_iASDU_Start + 44];
        m_sAnalyseResult +=  "\n采样速率：" + QString::number(m_iSmpRate,16);
        m_sAnalyseResult +=  "  配置版本号：" + getHexFormat(pkt_data[m_iASDU_Start + 45]);
        m_iTongDaoCount = TongDaoCount91;
        m_iTongDatCountReal = m_iTongDaoCount; //
        return true;
}

// 设置9-2规约的解析包参数
bool CapPacket::SetCapPara_92(const u_char* pkt_data, int pkt_len)
{
    makeSmvModle(pkt_data, pkt_len);

    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：9-2LE\n"  + m_sAnalyseResult;
        m_sGuiYueType = GuiYue9_2;
        m_iData_Length = 4;
        m_iTongDao_Length = 8;
        m_iSmpRate=CYPL/50;
    //    m_iSmpRate = myDB->getSmpRate92(m_bIsStandardPort);
   //     myDB->CloseDB();
  //      m_iSmpRate=100;
        int iLocation, j, iTemp, iLen_Temp;
        QString sPartName;
        //=============================================================
        // savPdu 段
        iTemp = 0, iLen_Temp = 0;
        iLocation = m_iAPDU_Start + 1;
        if(pkt_data[iLocation] > 0x80)
        {
                iLen_Temp = pkt_data[iLocation] - 0x80;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;		// 移动当前解析位置
        }else
                iTemp = pkt_data[iLocation];
        sPartName = "\nsavPdu：长度" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // ASDU数目
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80)
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                m_iASDU_Cnt = 0;
                for(j = 1; j <= iLen_Temp; j++)
                        m_iASDU_Cnt += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "\nASDU数目：" + QString::number(m_iASDU_Cnt,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // ASDU序列长度
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;

        if(pkt_data[iLocation] == 0xa2)        //9-2LE
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        iTemp = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                }
                else
                    iLen_Temp = 0;
                iLocation += iLen_Temp;
        }
        else                 //9-2
        {
            while (1)
            {
                iLocation += 1;
                if(pkt_data[iLocation] == 0xa2)
                {
                    iLocation += 1;
                    iTemp = pkt_data[iLocation];
                    if(iTemp > 0x80)
                    {
                            iLen_Temp = iTemp - 0x80;
                            iTemp = 0;
                            for(j = 1; j <= iLen_Temp; j++)
                                    iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                    }
                    else
                        iLen_Temp = 0;
                    iLocation += iLen_Temp;
                    break;
                }
            }
        }
        sPartName = "  ASDU序列长度：" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //==============================================================
        // 一个ASDU长度
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x30)
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        m_iASDU_Length = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                m_iASDU_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                }else
                {
                //    iLen_Temp = iTemp;
                        m_iASDU_Length = iTemp;
                }
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "  一个ASDU长度：" + QString::number(m_iASDU_Length,16);
        m_iASDU_Length += 2;
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80)         // svID
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                sPartName = "\nsvID：";
                for(j = 1; j <= iLen_Temp; j++)
                {
                    QString str;
                    str=QString(pkt_data[iLocation + j]);
                    sPartName +=str;
                }
                //    sPartName += QString::::Chr(pkt_data[iLocation + j]);
              //      sPartName += "a";pkt_data[iLocation + j]
                iLocation += iLen_Temp;
        }else
                return false;
        m_sAnalyseResult +=  sPartName;
        //===============================================================

        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;

        if(pkt_data[iLocation] == 0x81)         //dataset
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_iData_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_iData_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_iData_Length = iTemp;
            }
            iLocation += m_iData_Length;
        }
        else
            iLocation -= 1;

        iLocation += 1;
        if(pkt_data[iLocation] == 0x82)         // 采样计数
        {
                iLocation += 1;
                m_iFirstSmpCnt_Start = iLocation + 1;
                m_iSmpCnt_Length = pkt_data[iLocation];
                iLocation += m_iSmpCnt_Length;
        }else
        {

                return false;
        }
        //===============================================================        
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x83)         // 配置版本
        {
                iLocation += 1;
                iLen_Temp = pkt_data[iLocation];
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;
        }else
                return false;
        sPartName = "\n配置版本：" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x84)         //刷新时间refrTm
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_iRef_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_iRef_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_iRef_Length = iTemp;
            }
            iLocation += m_iRef_Length;
        }
        else
            iLocation -= 1;
        //==================================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x85)             // 采样同步
        {
                iLocation += 2;
                m_iSync_Start = iLocation;
                if(pkt_data[iLocation] == 0)
                        sPartName = "  同步状态：未同步";
                else
                        sPartName = "  同步状态：已同步";
        }else
                return false;
        m_sAnalyseResult +=  sPartName;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x86)         //采样速率smpRate
        {
            iLocation += 1;
            iTemp = pkt_data[iLocation];
            int m_ismpRate_Length=0;
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    for(j = 1; j <= iLen_Temp; j++)
                            m_ismpRate_Length += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            }else
            {
                m_ismpRate_Length = iTemp;
            }
            iLocation += m_ismpRate_Length;
        }
        else
            iLocation -= 1;
        //===============================================================
        iTemp = 0, iLen_Temp = 0;
        iLocation += 1;
        if(pkt_data[iLocation] == 0x87)             // 数据序列
        {
                iLocation += 1;
                iTemp = pkt_data[iLocation];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        iTemp = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                        iLocation = iLocation + iLen_Temp;
                }
        }else
                return false;
        sPartName = "  数据序列：长度" + QString::number(iTemp,16);
        m_iTongDaoCount = iTemp / m_iTongDao_Length;
        m_iTongDatCountReal = m_iTongDaoCount;
//        if(m_iTongDaoCount > 12) m_iTongDaoCount = 12;
        m_iFirstData_Start = iLocation + 1;			// 数据起始位置
        m_sAnalyseResult +=  sPartName;
        return true;
}

// 设置Goose规约的解析包参数
bool CapPacket::SetCapPara_Goose(const u_char* pkt_data, int pkt_len)
{
    int bbb=pkt_len;
    bbb++;
        m_sAnalyseResult = "规约类型：Goose\n"  + m_sAnalyseResult;
        m_sGuiYueType = GuiYue_Goose;
        m_iData_Length = 4;
        m_iTongDao_Length = 8;

        m_iSmpRate = 0;

        int iLocation, j, iTemp, iLen_Temp;
        QString sPartName;
        //=============================================================
        // *TL 段
        iTemp = 0, iLen_Temp = 0;
        iLocation = m_iAPDU_Start + 1;
        if(pkt_data[iLocation] > 0x80)
        {
                iLen_Temp = pkt_data[iLocation] - 0x80;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
                iLocation += iLen_Temp;		// 移动当前解析位置
        }else
                iTemp = pkt_data[iLocation];
        sPartName = "\n长度:" + QString::number(iTemp,16);
        m_sAnalyseResult +=  sPartName;

        ////////////////////////////////new
        iLocation += 1;
        if(pkt_data[iLocation] == 0x80) /////gocbRef字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\ngocbRef字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation++;
             //   sPartName+=getHexFormat(pkt_data[iLocation]);
                sPartName+= (pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x81) /////有效时间t
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int yxsj_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    yxsj_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName="\n有效时间t(ms):" + QString::number(yxsj_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x82) /////DatSet字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nDatSet字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation+=1;
                sPartName+=(pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x83) /////GoID字符串
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nGoID字符串:";
            for (j=0;j<iLen_Temp;j++)
            {
                iLocation+=1;
                sPartName+=(pkt_data[iLocation] & 0xFF);
            }
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x84) /////StNum
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            double st_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    st_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nStNum+1的时间t(ms):" + QString::number(st_tmp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x85) /////变化序列号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nStNum:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x86) /////报文顺序号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nSqNum:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x87) /////测试标志
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nTest:";
            iLocation+=1;
            if (pkt_data[iLocation]==0x01)
                sPartName+="TRUE";
            else
                sPartName+="FALSE";
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x88) /////配置版本号
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            iLocation += iLen_Temp;
            int xlh_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    xlh_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\nconfRev:" + QString::number(xlh_tmp,16);
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x89) /////未配置好标志
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            sPartName="\nndsCom:";
            iLocation+=1;

            if (pkt_data[iLocation]==0x01)
                sPartName+="TRUE";
            else
                sPartName+="FALSE";
            m_sAnalyseResult +=  sPartName;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0x8a) /////Goose单元个数
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
            int gs_tmp=0;
            for(j = 1; j <= iLen_Temp; j++)
                    gs_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\n总个数:" + QString::number(gs_tmp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        iLocation += 1;
        if(pkt_data[iLocation] == 0xab) /////Goose单元数据
        {
            iLocation += 1;
            iLen_Temp = pkt_data[iLocation];
         //   double gs_tmp=0;
         //   for(j = 1; j <= iLen_Temp; j++)
         //           gs_tmp += (pkt_data[iLocation + j] << (8 * (iLen_Temp - j)));
            sPartName = "\n长度:" + QString::number(iLen_Temp);
            m_sAnalyseResult +=  sPartName;
            iLocation += iLen_Temp;
        }
        //===========new
        //==============================================================
qDebug()<<m_sAnalyseResult;
        return true;
}
void CapPacket::setJqxs()
{
    int t=6;
    int num=m_iSmpRate;
    int N=num*t;
    int L=5*4*3*2*1;
    for(int m=0;m<N;m++)
    {
        ti[m]=(double)t*(m-(N+1)/2)/N;
        if (ti[m]<0)
            ti[m] *=-1;
        if(ti[m]>3|| ti[m]==3)
            ti[m]=0;
        else if((ti[m]>2 || ti[m]==2) && ti[m]<3)
          //  ti[m]=((3-ti[m])^5)/L;
            ti[m]=std::pow((3-ti[m]),5)/L;
        else if((ti[m]>1 || ti[m]==1) && ti[m]<2)
            ti[m]=std::pow((3-ti[m]),5)/L
                  -std::pow((2-ti[m]),5)*6/L;
        else
            ti[m]=std::pow((1-ti[m]),5)*9/L
                  -std::pow((2-ti[m]),5)*2/L
                  -std::pow(ti[m],5)*4/L
                  +std::pow((1+ti[m]),5)/L
                  +(1-ti[m]);
    }
}

// 捕获下一个包
bool CapPacket::CapNextPkt(void)
{
    static int computation_is_ok = 0;

    if(m_bInitCapPara)
    {
        struct pcap_pkthdr *header;	// 数据包头
        const u_char *pkt_data;		// 数据包
        int iData_Start;			// 数据位起始位
        int iSmpCnt_Start;			// SmpCount起始位
        int iSmpCnt;				// SmpCount值
        int iShuZiLiang;			// 数字量
        int res;
        if (m_iSmpRate<=0)
            m_iSmpRate=CYPL/50;
        if((res = pcap_next_ex(m_fp, &header, &pkt_data)) > 0)
        {                               // 符合规约标准
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
                    //qDebug()<<"cap para"<<m_iTongDao<<m_iZhouQi<<m_iTestedPoints;

                    for(int j = 0; j < m_iASDU_Cnt; j++)
                    {
                        if(m_bStopCap) return true;		// 外部阻止接口

                        int i;
                        iSmpCnt = 0;                // 获取SmpCount值
                        iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                        for(i = 0; i < m_iSmpCnt_Length; i++)
                            iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );

                         //qDebug()<<iSmpCnt;

                        //if(iSmpCnt == 2000)
                        if(iSmpCnt == 0)
                        {
                            //QTimer::singleShot(800, this, SLOT(cappacketIsReady()));
                            emit sigJswc();
                        }

                        m_Sync = pkt_data[m_iSync_Start];       //采样同步标志（仅对9-2有效）                        

                        if(m_iTongDao != TestChannel_PinLv)		// 状态为报文检验，无须分析数字量
                        {
                            //qDebug()<<"m_iTongDao != TestChannel_PinLv)"<<m_bSamplingPoints<<iSmpCnt;

                            if(! m_bSamplingPoints && iSmpCnt == m_iStartPoint)
                            //if(! m_bSamplingPoints && iSmpCnt == 0)
                            {
                                //qDebug()<<"if(! m_bSamplingPoints && iSmpCnt == 0)";

                                m_bSamplingPoints = true;
                                m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                m_iShuZiLiangMax_Temp = 0;
                                m_iTestedPoints = 0;
                                m_bCapIsNoError = true;

                                if(m_iTongDao != TestChannel_LuBo)
                                {
                                    qDebug()<<"paint cyclely!";
                                    emit sigCyOver();
                                }
                            }

                            if(m_bSamplingPoints)
                            {
                                //qDebug()<<" if(m_bSamplingPoints)";
                                int nLBound = (m_iTongDao / 12) * 12;	// 起始通道

                                //qDebug()<<m_iTongDao<<m_iTongDaoCount<<nLBound;

                                for (int k = 0; k < 12; k++)
                                {
                                    int kk = k + nLBound;	// 真实通道序号
                                    bool isNotEmpty = true;

                                    if(kk > m_iTongDaoCount - 1)
                                    {
                                        isNotEmpty = false;
                                        kk = m_iTongDaoCount;
                                    }

                                    //qDebug()<<"capNextPacket, kk="<<kk;

                                    iShuZiLiang = 0;
                                    iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * kk;
                                    for(i = 0; i < m_iData_Length; i++)
                                        iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                                    if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                                    iShuZiLiang += 0xFFFF0000;
                                    if(m_bIsChannelShow[k] || (m_iTongDao == TestChannel_LuBo))		// 计算可视通道的最大值
                                    {
                                        int iTemp = std::fabs(iShuZiLiang);
                                        if(iTemp > m_iShuZiLiangMax_Temp)
                                            m_iShuZiLiangMax_Temp = iTemp;

                                        if (isNotEmpty)
                                        {
                                            m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                                        }
                                        else
                                        {
                                            m_PointArray[k][m_iTestedPoints] = 0.0000000001;
                                        }
                                    }
                                    if (kk==m_iTongDao)
                                    {
                                        m_iTongDaoReal=k;

                                        if (testSelect==1)   //谐波测量时
                                        {
                                            m_dblSin += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * xieboNum * m_iTestedPoints / m_iSmpRate);
                                            m_dblCos += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * xieboNum * m_iTestedPoints / m_iSmpRate);
                                        }
                                        else
                                        {
                                            m_dblSin += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::sin(2 * PI * m_iTestedPoints / m_iSmpRate);
                                            m_dblCos += 2 / (double)m_iSmpRate * ((double)iShuZiLiang /1000) * std::cos(2 * PI * m_iTestedPoints / m_iSmpRate);
                                        }
                                   //     m_szl[m_iTestedPoints]=iShuZiLiang;

                                        //qDebug()<<"Sample"<<iSmpCnt<<iShuZiLiang;

                                    }
                                    if(m_bStopCap) return true;		// 外部停止接口
                                }
                                if(m_iTestedPoints < m_iZhouQi * m_iSmpRate - 1)
                                {
                                    if (m_iTestedPoints!=iSmpCnt)
                                        m_bCapIsNoError=false;

                                    //qDebug()<<"Tested points="<<m_iTestedPoints<<",iSmpCnt="<<iSmpCnt;
                                    m_iTestedPoints++;

                                    if(m_iTongDao==TestChannel_LuBo)
                                    {
                                        qDebug()<<"write dumpfile, m_iZhouqi="<<m_iTestedPoints;

                                        pcap_dump((unsigned char*)dumpfile,header,pkt_data); //写入
                                    }
                                }
                                else
                                {
                                    qDebug()<< "cycle done!";
                                    qDebug()<<m_bCapIsNoError<<testSelect<<m_iTongDao;

                                    if ((!m_bCapIsNoError) &&(testSelect==0))   //谐波测量时除外
                                    {
                                        m_bSamplingPoints = false;
                                        m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                        m_dblSin=0;
                                        m_dblCos=0;
                                        return true;
                                    }
                                    if(m_iTongDao==TestChannel_LuBo)
                                    {
                                        qDebug()<<"pcap_dump is done!"<<m_iShuZiLiangMax_Temp;

                                        pcap_dump((unsigned char*)dumpfile, header, pkt_data); //写入
                                        pcap_dump_close(dumpfile);   //关闭

                                        m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                        sigCyOver();

                                        //memcpy(m_tempArray,m_PointArray,sizeof(m_tempArray));
                                    }
                                    else
                                    {
                                        memcpy(m_tempArray,m_PointArray,sizeof(m_tempArray));

//                                        if (iSuanFa==0)
//                                        {
//                                            m_dblYouXiaoZhi = std::sqrt(m_dblSin * m_dblSin + m_dblCos * m_dblCos) * 1000
//                                                                        / std::sqrt(2) / m_dblFuZhi / (double)m_iZhouQiShu;
//                                            m_dblXW = GetXiangJiao(m_dblSin, m_dblCos) * 60;
//                                        }
//                                        else if (iSuanFa==1)
//                                        {
//                                            /*
//                                            int num=m_iSmpRate;
//                                            int N=num*6;
//                                            double vol=0;
//                                            for (int m=0;m<N;m++)
//                                                vol=vol+ti[m]*m_szl[m]*m_szl[m];
//                                            m_dblYouXiaoZhi=std::sqrt(vol/num) / m_dblFuZhi ;
//                                            m_dblXW = GetXiangJiao(m_dblSin, m_dblCos) * 60;
//                                            */
//                                        }
//                                        else if (iSuanFa==2)
//                                        {
//                                        //    harmonic(m_szl,1,m_iSmpRate*10,m_iSmpRate*50);
//                                            harmonic(m_tempArray[m_iTongDaoReal],harmonicOrder,m_iSmpRate*10,m_iSmpRate*50);   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
//                                        }
                                        if(computation_is_ok ==0 )
                                        {
                                            if(harmonicOrder < 5)
                                                computation_is_ok = 0;
                                            else if(harmonicOrder < 10)
                                                computation_is_ok = 3;
                                            else
                                                computation_is_ok = harmonicOrder /3;

                                            harmonic(m_tempArray[m_iTongDaoReal],harmonicOrder,m_iSmpRate*10,m_iSmpRate*50);
                                        }
                                        else
                                        {
                                            computation_is_ok --;
                                        }

                                        qDebug()<<"cappacket:CapNextPkt(),yxz, xw: "<< m_dblYouXiaoZhi << m_dblXW;
                                        //qDebug()<<"suanfa"<<iSuanFa<<m_dblFuZhi<<m_iSmpRate;
                                    }

                                    m_bSamplingPoints = false;
                                    m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                                    m_dblSin=0;
                                    m_dblCos=0;


                                    setIsOK(true);
                                    if(m_iTongDao==TestChannel_LuBo)
                                    {
                                        StopCap(true);
                                    }
                                    return true;		// 经过一次成功的采集
                                }
                            }
                        }
                        else      // 状态为报文检验，无须分析数字量 主要为报文校验
                        {
                            if (jsFlag==-1)
                            {
                                jsFlag=0;
                                m_iJs=0;
                                m_iJs=iSmpCnt;
                            }
                            else
                            {
                                endm=header->ts.tv_usec;
                              //  qDebug()<<endm;
                                double timeuse=endm-startm;
                                if(timeuse<0)
                                    timeuse +=1000000;
                              //  qDebug()<<iSmpCnt<<" "<<header->ts.tv_sec<<"."<<header->ts.tv_usec;
                                if (m_iType==1)
                                {
                                    if (timeuse>dblMaxJg)
                                        dblMaxJg=timeuse;
                                    if (timeuse<dblMinJg)
                                        dblMinJg=timeuse;
                                }
                                else
                                {                                    
                                    m_iJs++;
                                    if (iSmpCnt==0)
                                        m_iJs=0;
                                    int iCnt=m_iJs-iSmpCnt;
                                    if (iCnt>0)
                                    {
                                        iCnt= m_iSmpRate * 50 - m_iJs + iSmpCnt;
                                        if (iCnt<0)
                                        {
                                            iCnt= 65536 - m_iJs + iSmpCnt;
                                        }
                                        m_iLost+=iCnt;
                                        m_iJs=iSmpCnt;
                                    }
                                    else if (iCnt<0)
                                    {
                                        m_iLost+=std::abs(iCnt);
                                        m_iJs=iSmpCnt;
                                    }
                                }
                            }
                            startm=header->ts.tv_usec;
                            m_iTestedPoints++;
                            if(m_iTestedPoints >= m_iZhouQi * m_iSmpRate - 1)       //m_iZhouQi个周期结束
                            {
                                m_iTestedPoints=0;
                            }

                        }          //
                    }
               // }
            }
        }
    }
    return false;
}

#if 0
void CapPacket::harmonic(double *s,int M,int len,int fs)   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
{
/*
    double sig1[320]={
    1.382162,1.411154,1.421225,1.418173,1.411154,1.397421,1.375143,1.337911,1.300069,1.251545,1.204242,1.149615,1.076066,0.987869,0.903029,0.818799,0.717784,0.638132,0.547494,0.420233,0.339666,0.206607,0.095216,-0.012818,-0.127565,
    -0.225528,-0.343633,-0.442206,-0.559091,-0.661021,-0.757153,-0.847486,-0.934157,-1.014420,-1.090410,-1.165789,-1.217365,-1.291218,-1.308309,-1.349203,-1.377584,-1.397726,-1.410239,-1.413901,-1.407797,-1.380636,-1.365072,-1.336995,
    -1.293660,-1.249714,-1.195697,-1.137407,-1.068742,-0.970779,-0.892653,-0.816052,-0.719921,-0.626841,-0.535286,-0.409247,-0.314336,-0.208133,-0.090639,0.018616,0.130922,0.230411,0.348516,0.471199,0.542000,0.679942,0.754711,0.843824,
    0.937209,1.013504,1.086442,1.151446,1.216144,1.257954,1.317464,1.336385,1.365377,1.404135,1.408408,1.416342,1.408408,1.398337,1.382162,1.360189,1.317464,1.258259,1.197833,1.132830,1.062638,0.995804,0.918288,0.809339,0.733349,0.627451,
    0.526436,0.437629,0.316167,0.216678,0.094911,-0.014649,-0.125734,-0.228580,-0.343023,-0.464485,-0.553597,-0.668650,-0.759594,-0.830701,-0.927443,-1.018692,-1.085527,-1.156023,-1.213703,-1.263447,-1.307698,-1.341878,-1.372396,-1.397421,
    -1.405661,-1.412375,-1.409323,-1.390097,-1.373312,-1.339132,-1.291524,-1.229877,-1.181964,-1.134051,-1.063249,-0.986038,-0.906081,-0.812390,-0.703136,-0.620432,-0.522774,-0.418402,-0.301518,-0.193484,-0.086366,0.024109,0.130922,0.239872,
    0.355535,0.455634,0.557870,0.652171,0.755627,0.839246,0.931106,1.022660,1.109941,1.141375,1.216144,1.261006,1.315938,1.343709,1.369345,1.387961,1.412680,1.413901,1.397726,1.388876,1.369039,1.339437,1.307088,1.249714,1.188373,1.111772,1.051041,
    0.990311,0.904555,0.821241,0.725414,0.617075,0.512398,0.419623,0.317998,0.204776,0.091859,-0.016480,-0.133059,-0.247501,-0.343633,-0.454108,-0.563973,-0.657969,-0.755932,-0.845655,-0.935378,-1.015030,-1.081559,-1.157855,-1.204242,-1.256733,-1.305257,
    -1.351644,-1.379416,-1.396811,-1.407797,-1.409628,-1.407492,-1.410849,-1.368734,-1.336385,-1.293355,-1.247883,-1.190204,-1.122759,-1.069352,-1.005875,-0.912795,-0.813306,-0.725719,-0.622263,-0.515450,-0.428168,-0.299992,-0.195010,-0.092164,0.028077,
    0.135195,0.244144,0.351873,0.453498,0.542000,0.646067,0.749828,0.844434,0.928969,1.012894,1.084001,1.148394,1.204852,1.266499,1.301289,1.339742,1.377890,1.408713,1.415427,1.409323,1.408103,1.387961,1.364462,1.359884,1.316243,1.250629,1.196612,1.130388,
    1.058976,0.992752,0.921340,0.823072,0.724498,0.625315,0.527352,0.421454,0.316167,0.205081,0.095827,-0.009461,-0.138552,-0.240787,-0.344549,-0.447089,-0.547799,-0.663767,-0.768139,-0.844434,-0.943923,-1.012284,-1.084611,-1.158160,-1.211872,-1.262226,
    -1.300984,-1.346151,-1.369955,-1.385824,-1.412375,-1.415427,-1.409018,-1.398337,-1.373007,-1.355306,-1.297017,-1.251240,-1.194171,-1.134661,-1.062943,-0.991226,-0.901198,-0.812696,-0.718395,-0.625925,-0.526436,-0.419928,-0.308843,-0.212100,-0.093690,
    0.023804,0.133974,0.238651,0.352483,0.455940,0.551156,0.664073,0.758679,0.841382,0.932021,1.032731,1.079423,1.155718,1.217365,1.269856,1.315023,1.348898
    };
    s=sig1;
    */
        int p,n,j,k;
        double a,b;
        int f0;
        double y,y2,maxu;
        long k0;

    //    double A[40];
        double B[40];
        double C[40];

        f0=50;
        double r[len];
        memset(r,0,len);
     //   QString sm="";
        for(p=0;p<len;p++)
        {
            //r[p]=s[p]*(0.42-0.5*std::cos(2*PI*p/len)+0.08*std::cos(4*PI*p/len));
  //          sm =sm+ QString::number(s[p])+" ";
            r[p]=s[p] *(0.3125-0.46875*std::cos(2*PI*p/len)+0.1875*std::cos(4*PI*p/len)-0.03125*std::cos(6*PI*p/len));//FDMS_1 Window
        }
  //      qDebug()<<sm;
       // qDebug()<<s[0]<<":"<<s[1];

        //int tm=len/m_iSmpRate+4;
        int tm=len*M/m_iSmpRate + 4;//M=1,tm=14;M=40,tm=404;

        double L[tm];
        double T[tm];
        for(p=0;p<tm;p++)
        {
            L[p]=0;
            T[p]=0;
            for(n=0;n<len;n++)
            {
                T[p]=T[p]+r[n]*std::cos(2*PI*p*n/len);
                L[p]=L[p]+r[n]*std::sin(2*PI*p*n/len);
            }
        }
        double u[len];
        for(p=0;p<len;p++)
        {
            u[p]=std::sqrt(L[p]*L[p]+T[p]*T[p]);
        }

        for(p=0;p<M;p++)
        {
                k0=std::ceil(f0*(p+1)*len/fs);
                maxu=u[k0];
                k=k0;
                for(j=k0-3;j<k0+3;j++)
                {
                        if(maxu<u[j])
                        {
                                maxu=u[j];//first high of freq spectrum
                                k=j;
                        }
                }

                if(u[k-1]>u[k+1])  k=k-1;//second high of freq	spectrum

                y=u[k];
                y2=u[k+1];
                b=(y2-y)/(y2+y);
                a=3.5*b;

                // B[p]=(k+a+0.5)*fs/len;//freq of signal

                B[p]=(y+y2)*(3.43612+0.85434*std::pow(a,2)+0.11871*std::pow(a,4))/len;//RMS of signal

                if(T[k]>0)
                    C[p]=std::acos(L[k]/u[k])-(a+0.5)*PI;//phase of angel,range of angel is 0-2*PI
                else if(T[k]<0)
                    C[p]=2*PI-std::acos(L[k]/u[k])-(a+0.5)*PI;
                else if(T[k]==0)
                {
                     if(L[k]>=0)   C[p]=-(a+0.5)*PI;
                     else    C[p]=PI-(a+0.5)*PI;
                }
        }

        m_dblYouXiaoZhi=B[0]/1.4142135623/m_dblFuZhi;
     //   m_dblYouXiaoZhi=B[0]/1.4142135623/2000;
        m_dblXW=C[0]*180*60/PI;
        if (m_dblXW<0)
            m_dblXW+=360*60;
                //C[0]初相角  B[0]/1.4142135623 有效值
 //       qDebug()<<A[0];
}
#endif
void CapPacket::harmonic(double *s,int M,int len,int fs)   //s 所有的点 M：谐波次数（可以不用）len smrate*zhouqi fs smrate*50
{
/*
    double sig1[320]={
    1.382162,1.411154,1.421225,1.418173,1.411154,1.397421,1.375143,1.337911,1.300069,1.251545,1.204242,1.149615,1.076066,0.987869,0.903029,0.818799,0.717784,0.638132,0.547494,0.420233,0.339666,0.206607,0.095216,-0.012818,-0.127565,
    -0.225528,-0.343633,-0.442206,-0.559091,-0.661021,-0.757153,-0.847486,-0.934157,-1.014420,-1.090410,-1.165789,-1.217365,-1.291218,-1.308309,-1.349203,-1.377584,-1.397726,-1.410239,-1.413901,-1.407797,-1.380636,-1.365072,-1.336995,
    -1.293660,-1.249714,-1.195697,-1.137407,-1.068742,-0.970779,-0.892653,-0.816052,-0.719921,-0.626841,-0.535286,-0.409247,-0.314336,-0.208133,-0.090639,0.018616,0.130922,0.230411,0.348516,0.471199,0.542000,0.679942,0.754711,0.843824,
    0.937209,1.013504,1.086442,1.151446,1.216144,1.257954,1.317464,1.336385,1.365377,1.404135,1.408408,1.416342,1.408408,1.398337,1.382162,1.360189,1.317464,1.258259,1.197833,1.132830,1.062638,0.995804,0.918288,0.809339,0.733349,0.627451,
    0.526436,0.437629,0.316167,0.216678,0.094911,-0.014649,-0.125734,-0.228580,-0.343023,-0.464485,-0.553597,-0.668650,-0.759594,-0.830701,-0.927443,-1.018692,-1.085527,-1.156023,-1.213703,-1.263447,-1.307698,-1.341878,-1.372396,-1.397421,
    -1.405661,-1.412375,-1.409323,-1.390097,-1.373312,-1.339132,-1.291524,-1.229877,-1.181964,-1.134051,-1.063249,-0.986038,-0.906081,-0.812390,-0.703136,-0.620432,-0.522774,-0.418402,-0.301518,-0.193484,-0.086366,0.024109,0.130922,0.239872,
    0.355535,0.455634,0.557870,0.652171,0.755627,0.839246,0.931106,1.022660,1.109941,1.141375,1.216144,1.261006,1.315938,1.343709,1.369345,1.387961,1.412680,1.413901,1.397726,1.388876,1.369039,1.339437,1.307088,1.249714,1.188373,1.111772,1.051041,
    0.990311,0.904555,0.821241,0.725414,0.617075,0.512398,0.419623,0.317998,0.204776,0.091859,-0.016480,-0.133059,-0.247501,-0.343633,-0.454108,-0.563973,-0.657969,-0.755932,-0.845655,-0.935378,-1.015030,-1.081559,-1.157855,-1.204242,-1.256733,-1.305257,
    -1.351644,-1.379416,-1.396811,-1.407797,-1.409628,-1.407492,-1.410849,-1.368734,-1.336385,-1.293355,-1.247883,-1.190204,-1.122759,-1.069352,-1.005875,-0.912795,-0.813306,-0.725719,-0.622263,-0.515450,-0.428168,-0.299992,-0.195010,-0.092164,0.028077,
    0.135195,0.244144,0.351873,0.453498,0.542000,0.646067,0.749828,0.844434,0.928969,1.012894,1.084001,1.148394,1.204852,1.266499,1.301289,1.339742,1.377890,1.408713,1.415427,1.409323,1.408103,1.387961,1.364462,1.359884,1.316243,1.250629,1.196612,1.130388,
    1.058976,0.992752,0.921340,0.823072,0.724498,0.625315,0.527352,0.421454,0.316167,0.205081,0.095827,-0.009461,-0.138552,-0.240787,-0.344549,-0.447089,-0.547799,-0.663767,-0.768139,-0.844434,-0.943923,-1.012284,-1.084611,-1.158160,-1.211872,-1.262226,
    -1.300984,-1.346151,-1.369955,-1.385824,-1.412375,-1.415427,-1.409018,-1.398337,-1.373007,-1.355306,-1.297017,-1.251240,-1.194171,-1.134661,-1.062943,-0.991226,-0.901198,-0.812696,-0.718395,-0.625925,-0.526436,-0.419928,-0.308843,-0.212100,-0.093690,
    0.023804,0.133974,0.238651,0.352483,0.455940,0.551156,0.664073,0.758679,0.841382,0.932021,1.032731,1.079423,1.155718,1.217365,1.269856,1.315023,1.348898
    };
    s=sig1;
    */
        int p,n,j,k;
        double a,b;
        int f0;
        double y,y2,maxu;
        long k0;

    //    double A[40];
        double B[40];
        double C[40];

        f0=50;
        double r[len];
        memset(r,0,len);
     //   QString sm="";
        for(p=0;p<len;p++)
        {
            //r[p]=s[p]*(0.42-0.5*std::cos(2*PI*p/len)+0.08*std::cos(4*PI*p/len));
  //          sm =sm+ QString::number(s[p])+" ";
            r[p]=s[p] *(0.3125-0.46875*std::cos(2*PI*p/len)+0.1875*std::cos(4*PI*p/len)-0.03125*std::cos(6*PI*p/len));//FDMS_1 Window
        }
  //      qDebug()<<sm;
       // qDebug()<<s[0]<<":"<<s[1];

        //int tm=len/m_iSmpRate+4;
        if(M > 8) len = len /2;

        int tm=len*M/m_iSmpRate + 4;//M=1,tm=14;M=40,tm=404;

        double L[tm];
        double T[tm];
        for(p=0;p<tm;p++)
        {
            L[p]=0;
            T[p]=0;
            for(n=0;n<len;n++)
            {
                T[p]=T[p]+r[n]*std::cos(2*PI*p*n/len);
                L[p]=L[p]+r[n]*std::sin(2*PI*p*n/len);
            }
        }
        double u[tm];
        for(p=0;p<tm;p++)
        {
            u[p]=std::sqrt(L[p]*L[p]+T[p]*T[p]);
        }

        for(p=0;p<M;p++)
        {
                k0=std::ceil(f0*(p+1)*len/fs);
                maxu=u[k0];
                k=k0;
                for(j=k0-3;j<k0+3;j++)
                {
                        if(maxu<u[j])
                        {
                                maxu=u[j];//first high of freq spectrum
                                k=j;
                        }
                }

                if(u[k-1]>u[k+1])  k=k-1;//second high of freq	spectrum

                y=u[k];
                y2=u[k+1];
                b=(y2-y)/(y2+y);
                a=3.5*b;

                // B[p]=(k+a+0.5)*fs/len;//freq of signal

                B[p]=(y+y2)*(3.43612+0.85434*std::pow(a,2)+0.11871*std::pow(a,4))/len;//RMS of signal

                if(T[k]>0)
                    C[p]=std::acos(L[k]/u[k])-(a+0.5)*PI;//phase of angel,range of angel is 0-2*PI
                else if(T[k]<0)
                    C[p]=2*PI-std::acos(L[k]/u[k])-(a+0.5)*PI;
                else if(T[k]==0)
                {
                     if(L[k]>=0)   C[p]=-(a+0.5)*PI;
                     else    C[p]=PI-(a+0.5)*PI;
                }
        }

        m_dblYouXiaoZhi=B[M-1]/1.4142135623/m_dblFuZhi;
     //   m_dblYouXiaoZhi=B[0]/1.4142135623/2000;
        m_dblXW=C[M-1]*180*60/PI;
        if (m_dblXW<0)
            m_dblXW+=360*60;
                //C[0]初相角  B[0]/1.4142135623 有效值
 //       qDebug()<<A[0];
}

QString CapPacket::getHexFormat(int iValue)
{
        QString sRes;
     //   sRes = iValue.ToString("X");
        sRes=QString::number(iValue,16);
        if(iValue < 0x10)
                sRes = "0" + sRes;
        return sRes;
}

// void CapPacket::pcap_lubo()
// {
//    QDateTime time = QDateTime::currentDateTime();
//    QString str =time.toString("yyyy-MM-dd hh:mm:ss");     //yyyy-MM-dd hh:mm:ss ddd
//    QString fa=str +".pcap";

//    QDir toDir = QDir::currentPath();
//    toDir.mkdir("pcap");
//    fa =toDir.currentPath() +"/pcap/" +fa;
//    m_sFileLuboName=fa;
//    QByteArray ba = fa.toLatin1();
//    char *fname=ba.data();
//    dumpfile = pcap_dump_open(m_fp, fname);

//    pcap_loop(m_fp, 0, packet_handler, (unsigned char *)dumpfile);
// }

void CapPacket::pcap_lubo()
{
    QDateTime time = QDateTime::currentDateTime();

    QString str = time.toString("yyyy-MM-dd-hh-mm-ss");

    QString filename = str + ".pcap";

    QDir toDir= QDir::currentPath();

    if(toDir.exists("c://pcap"))
    {
        qDebug() << "/pcap/ is existed!";

        toDir.setPath("c://model-1000/pcap");
        toDir.setFilter(QDir::Files);
        toDir.setSorting(QDir::Time);

        QFileInfoList list = toDir.entryInfoList();

        int i = 0;
        for(i=0 ; i<list.size(); i++)
        {
            if(i > 20)
            {
                QFileInfo fileInfo = list.at(i);
                toDir.remove( fileInfo.fileName() );

                qDebug() << "Deleted file: "<<fileInfo.fileName();
            }
        }
    }
    else
    {
        qDebug() << "mkdir pcap";
        toDir.mkdir("c://model-1000/pcap");
        toDir.setPath("c://model-1000/pcap");
    }

    filename = toDir.absolutePath()+ "/" + filename;
    QByteArray ba = filename.toLatin1();
    char *fname = ba.data();
    dumpfile = pcap_dump_open(m_fp, fname);
}

void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
 /* 此函数功能将数据报存储到堆文件 */
 pcap_dump(dumpfile, header, pkt_data);
}
void CapPacket::pcap_stopLubo()
{
    if (m_fp>0)
        pcap_breakloop(m_fp);
}
void CapPacket::pcap_openFile(QString sfile)
{
    pcap_t *fd;
    char *err;
    int res;
    int icypl=0;
    int iData_Start;			// 数据位起始位
    int iSmpCnt_Start;			// SmpCount起始位
    int iSmpCnt;			// SmpCount值
    int iShuZiLiang;			// 数字量
    bool bInit=true;
    int iZhouQi=0;
    QByteArray ba = sfile.toLatin1();
    const char *file=ba.data();
    fd=pcap_open_offline(file,err);
    pcap_pkthdr * header;
    const u_char *pkt_data;

    while(1)
    {
        res=pcap_next_ex(fd,&header,&pkt_data);
        if ((res< 1)||(header->len < 30))
        {
            m_sAnalyseResult = "端口打开失败！";
            break;
        }
        else
        {
            unsigned int i, j;
            bool IsYiTaiWang;
            int ethType;//0:sv;1:goose;
            IsYiTaiWang = false;
            ethType=0;
            for(i = 0; i <= header->len && i <= YI_TAI_WANG_START_MAX; i++)
            {
                    //=======================================================
                    // 以太网标志
                    if (pkt_data[i] == 0x88 && ((pkt_data[i + 1] == 0xba) ||(pkt_data[i + 1] == 0xb8)))
                    {
                            if(i > 11)
                            {
                                    IsYiTaiWang = true;
                                    if (pkt_data[i + 1] == 0xb8)
                                        ethType=1;
                                    QString sDestination = "目的地址：", sSource = "  源 地 址：";
                                    for(j = 0; j < 6; j++)
                                    {
                                            sDestination += getHexFormat(pkt_data[j]) + " ";
                                            sSource += getHexFormat(pkt_data[j + 6]) + " ";
                                    }
                                    m_sAnalyseResult = sDestination;
                                    m_sAnalyseResult += sSource;
                                    QString sTPID = "\nTPID：", sTCI = "  TCI：";
                                    if(i >= 14) sTPID += getHexFormat(pkt_data[12]) + " " + getHexFormat(pkt_data[13]);
                                    if(i >= 16)	sTCI += getHexFormat(pkt_data[14]) + " " + getHexFormat(pkt_data[15]);
                                    m_sAnalyseResult += sTPID;
                                    m_sAnalyseResult += sTCI;
                                    break;
                            }else
                            {
                                    if(i < 11) continue;
                            }
                    }
            }
            if(IsYiTaiWang)
            {
                QString  sTemp;
                if (ethType==0)
                    m_sAnalyseResult += "\n以太网类：88 ba";
                else if (ethType==1)
                    m_sAnalyseResult += "\n以太网类：88 b8";

                        sTemp = "  APPID：" + getHexFormat(pkt_data[i + 2]) + " " + getHexFormat(pkt_data[i + 3]);
                        m_sAnalyseResult += sTemp;
                        sTemp = "  LENGTH：";
                        int iLength = (pkt_data[i + 4] << 8) + pkt_data[i + 5];
                        sTemp += QString::number(iLength,16);
                        m_sAnalyseResult += sTemp;
                        sTemp = "\n保留1：" + getHexFormat(pkt_data[i + 6]) + " " + getHexFormat(pkt_data[i + 7]);
                        m_sAnalyseResult += sTemp;
                        sTemp = "  保留2：" + getHexFormat(pkt_data[i + 8]) + " " + getHexFormat(pkt_data[i + 9]);
                        m_sAnalyseResult +=  sTemp;
                        if (pkt_data[i + 10] == 0x80)
                        {
                            m_sAnalyseResult +=  "\nTag：80";
                            m_iAPDU_Start = i + 10;
                            SetCapPara_91(pkt_data, header->len);
                        }
                        else if(pkt_data[i + 10] == 0x60)
                        {
                            m_sAnalyseResult +=  "\nTag：60";
                            m_iAPDU_Start = i + 10;
                            SetCapPara_92(pkt_data, header->len);
                        }
                        else
                        {
                            m_sAnalyseResult +=  "\n非9-1或9-2数据！";
                            bInit = false;
                        }
                        break;
            }
            else            //IsYiTaiWang
            {
                bInit = false;
                m_sAnalyseResult = "非以太网数据！";
                m_sGuiYueType = NotEthernet;
            }
        }
    }
    if (bInit)
    {
        fd=pcap_open_offline(file,err);
        while(1)
        {
            res=pcap_next_ex(fd,&header,&pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                break;
            }
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
                for(int j = 0; j < m_iASDU_Cnt; j++)
                {
                    int i;
                    iSmpCnt = 0;                // 获取SmpCount值
                    iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
                    for(i = 0; i < m_iSmpCnt_Length; i++)
                        iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
                    if (iSmpCnt>icypl)
                        icypl=iSmpCnt;
                    if (iSmpCnt==0)
                        iZhouQi++;
                }
            }
        }
        if (icypl>12700)
            icypl=12800;
        else if (icypl>3990)
            icypl=4000;
        m_iSmpRate=icypl/50;
        fd=pcap_open_offline(file,err);
        m_iShuZiLiangMax_Temp = 0;
        while(1)
        {
            res=pcap_next_ex(fd,&header,&pkt_data);
            if ((res< 1)||(header->len < 30))
            {
                m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                qDebug()<<"paint in open_pcap_file!";
                emit sigCyOver();
                break;
            }
            if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
            {
        for(int j = 0; j < m_iASDU_Cnt; j++)
        {
            int i;
            iSmpCnt = 0;                // 获取SmpCount值
            iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);
            for(i = 0; i < m_iSmpCnt_Length; i++)
                iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
            m_Sync = pkt_data[m_iSync_Start];       //采样同步标志（仅对9-2有效）

                if(! m_bSamplingPoints && iSmpCnt == m_iStartPoint)
                {
                    m_bSamplingPoints = true;


                    m_iTestedPoints = 0;
                }
                if(m_bSamplingPoints)
                {
                  int nLBound =0;//  int nLBound = m_iTongDao / m_iTongDaoCount * m_iTongDaoCount;	// 起始通道
                    for (int k = 0; k < 12; k++)
                    {
                        int kk = k + nLBound;	// 真实通道序号
                        iShuZiLiang = 0;
                        iData_Start = m_iFirstData_Start + j * m_iASDU_Length + m_iTongDao_Length * kk;
                        for(i = 0; i < m_iData_Length; i++)
                            iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                        if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                        iShuZiLiang += 0xFFFF0000;
                        if(m_bIsChannelShow[k])		// 计算可视通道的最大值
                        {
                            qDebug()<<" if(m_bIsChannelShow[k])"<<k;
                            int iTemp = std::fabs(iShuZiLiang);
                            if(iTemp > m_iShuZiLiangMax_Temp)
                                m_iShuZiLiangMax_Temp = iTemp;
                       //     qDebug()<<k<<" "<<m_iTestedPoints<<" "<<iShuZiLiang;
                            m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                        }
                    }
                    if(m_iTestedPoints < iZhouQi * 50 * m_iSmpRate - 1)
                    {
                        m_iTestedPoints++;
                    }
                    else
                    {
                        m_bSamplingPoints = false;
                    }
                }
            }
    }
        }
    }
}


bool CapPacket::makeSmvModle(const u_char* pkt_data, int pkt_len)
{
    bool is_92_le = true;

    show_packet = "";

    for(int i = 0; i < pkt_len; i++)
    {
        show_packet += getHexFormat(pkt_data[i]);
        show_packet += " ";
    }

    //qDebug()<< show_packet;

    show_protocol = new QStandardItemModel();
    show_protocol->setColumnCount(3);
    show_protocol->setRowCount(0);
    show_protocol->setHeaderData(0,Qt::Horizontal,tr("Name"));
    show_protocol->setHeaderData(1,Qt::Horizontal,tr("Data"));
    show_protocol->setHeaderData(2,Qt::Horizontal,tr("Value"));

    int pos = 0;
    QString mac_data_dst, mac_data_snd;
    QString mac_dst, mac_snd;

    mac_data_dst = mac_data_snd = "0x";
    mac_snd = mac_dst = "";

    for(pos = 0; pos < 6; pos++)
    {
        mac_data_dst += getHexFormat(pkt_data[pos]);
        mac_dst += getHexFormat(pkt_data[pos]);
        mac_dst += ":";
    }
    mac_dst = mac_dst.left(mac_dst.length() - 1);
    qDebug()<<"mac_dst"<<mac_dst;

    QList<QStandardItem *> items0;

    QStandardItem *item00 = new QStandardItem(QString("目的MAC"));
    items0.append(item00);
    QStandardItem *item01 = new QStandardItem(mac_data_dst);
    items0.append(item01);
    QStandardItem *item02 = new QStandardItem(mac_dst);
    items0.append(item02);

    show_protocol->appendRow(items0);

    for(;pos < 12; pos++)
    {
        mac_data_snd += getHexFormat(pkt_data[pos]);
        mac_snd += getHexFormat(pkt_data[pos]);
        mac_snd += ":";
    }
    mac_snd = mac_snd.left(mac_snd.length() - 1);
    qDebug()<<"mac_snd"<<mac_snd;

    QList<QStandardItem *> items1;

    QStandardItem *item10 = new QStandardItem(QString("设备MAC"));
    items1.append(item10);
    QStandardItem *item11 = new QStandardItem(mac_data_snd);
    items1.append(item11);
    QStandardItem *item12 = new QStandardItem(mac_snd);
    items1.append(item12);

    show_protocol->appendRow(items1);

    qDebug()<<"ether type:"<<QString::number(pkt_data[pos],16)<<QString::number( pkt_data[pos+1],16);

    QList<QStandardItem *> items2;

    if(pkt_data[pos] != 0x81)
    {
        QStandardItem *item20 = new QStandardItem(QString("VLAN"));
        items2.append(item20);
        QStandardItem *item21 = new QStandardItem("");
        items2.append(item21);
        QStandardItem *item22 = new QStandardItem("无");
        items2.append(item22);
    }
    else
    {
        pos += 2;

        QString vlan_data="0x";
        vlan_data += getHexFormat(pkt_data[pos]);
        vlan_data += getHexFormat(pkt_data[++pos]);

        QStandardItem *item20 = new QStandardItem(QString("VLAN"));
        items2.append(item20);
        QStandardItem *item21 = new QStandardItem(vlan_data);
        items2.append(item21);
        QStandardItem *item22 = new QStandardItem("");
        items2.append(item22);

        pos++;
    }
    show_protocol->appendRow(items2);

    //=============================================================
    // appid
    pos += 2;
    QString appid_data = "0x";
    appid_data +=  getHexFormat(pkt_data[pos]);
    appid_data +=  getHexFormat(pkt_data[++pos]);

    QList<QStandardItem *> items3;

    QStandardItem *item30 = new QStandardItem(QString("APPID"));
    items3.append(item30);
    QStandardItem *item31 = new QStandardItem(appid_data);
    items3.append(item31);
    QStandardItem *item32 = new QStandardItem("");
    items3.append(item32);

    show_protocol->appendRow(items3);

    pos += 8;

    //=============================================================
    // savPdu length
    int iTemp = 0, iLen_Temp = 0;
    int j = 0, i = 0;

    if(pkt_data[pos] > 0x80)
    {
            iLen_Temp = pkt_data[pos] - 0x80;
            for(j = 1; j <= iLen_Temp; j++)
                    iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
            pos += iLen_Temp;		// 移动当前解析位置
    }else
            iTemp = pkt_data[pos];

    //==============================================================
    // ASDU数目
    iTemp = 0, iLen_Temp = 0;
    int num_of_asdu = 0;

    pos += 1;

    if(pkt_data[pos] == 0x80)
    {
            pos += 1;
            iLen_Temp = pkt_data[pos];
            for(j = 1; j <= iLen_Temp; j++)
                    num_of_asdu += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
            pos += iLen_Temp;
    }else
            return false;

    QList<QStandardItem *> items4;

    QStandardItem *item40 = new QStandardItem(QString("ASDU"));
    items4.append(item40);
    QStandardItem *item41 = new QStandardItem("");
    items4.append(item41);
    QStandardItem *item42 = new QStandardItem(QString::number(num_of_asdu)+" 个");
    items4.append(item42);

    show_protocol->appendRow(items4);

    // squence of ASDU , the length
    pos++;

    if(pkt_data[pos] != 0xa2)
    {
        is_92_le = false;

        while (1)
        {
            pos += 1;
            if(pkt_data[pos] == 0xa2)
            {
                pos += 1;
                iTemp = pkt_data[pos];
                if(iTemp > 0x80)
                {
                        iLen_Temp = iTemp - 0x80;
                        iTemp = 0;
                        for(j = 1; j <= iLen_Temp; j++)
                                iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
                }
                else
                    iLen_Temp = 0;
                pos += iLen_Temp;
                break;
            }
        }
    }
    else
    {
        pos += 1;
        iTemp = pkt_data[pos];
        if(iTemp > 0x80)
        {
                iLen_Temp = iTemp - 0x80;
                iTemp = 0;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
        }
        else
            iLen_Temp = 0;
        pos += iLen_Temp;
    }

//    sPartName = "  ASDU序列长度：" + QString::number(iTemp,16);
//    m_sAnalyseResult +=  sPartName;
    //==============================================================
    // 一个ASDU长度
    iTemp = 0, iLen_Temp = 0;
    pos += 1;
    if(pkt_data[pos] == 0x30)
    {
            pos += 1;
            iTemp = pkt_data[pos];
            if(iTemp > 0x80)
            {
                    iLen_Temp = iTemp - 0x80;
                    iTemp = 0;
                    for(j = 1; j <= iLen_Temp; j++)
                            iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
            }

//            m_iASDU_Length = iTemp;

            pos += iLen_Temp;
    }
    else
    {
        return false;
    }
//    sPartName = "  一个ASDU长度：" + QString::number(m_iASDU_Length,16);
//    m_iASDU_Length += 2;
//    m_sAnalyseResult +=  sPartName;
    //===============================================================
    QString str_svid_data = "0x";
    QString str_svid = "";

    iTemp = 0, iLen_Temp = 0;
    pos += 1;
    if(pkt_data[pos] == 0x80)         // svID
    {
            pos += 1;
            iLen_Temp = pkt_data[pos];
            for(j = 1; j <= iLen_Temp; j++)
            {
                str_svid_data += getHexFormat(pkt_data[pos + j]);
                str_svid += QString(pkt_data[pos + j]);
            }
            pos += iLen_Temp;
    }else
            return false;

    QList<QStandardItem *> childItems1;

    QStandardItem *childItems10 = new QStandardItem(QString("SvID"));
    childItems1.append(childItems10);

    QStandardItem *childItems11 = new QStandardItem(str_svid_data);
    childItems1.append(childItems11);

    QStandardItem *childItems12 = new QStandardItem(str_svid);
    childItems1.append(childItems12);

    items4.at(0)->appendRow(childItems1);
//    m_sAnalyseResult +=  sPartName;
//    //===============================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;

    if(pkt_data[pos] == 0x81)         //dataset
    {
        is_92_le = false;
        QString str_dataset_data = "0x";
        QString str_dataset = "";

        pos += 1;
        iTemp = pkt_data[pos];
        if(iTemp > 0x80)
        {
                iLen_Temp = iTemp - 0x80;
                iTemp = 0;
                for(j = 1; j <= iLen_Temp; j++)
                        iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));

                pos += iLen_Temp;
        }

        for(j = 1; j <= iTemp; j++)
            str_dataset_data += getHexFormat(pkt_data[pos + j]);

        QList<QStandardItem *> childItems2;

        QStandardItem *childItems20 = new QStandardItem(QString("dataset"));
        childItems2.append(childItems20);

        QStandardItem *childItems21 = new QStandardItem(str_dataset_data);
        childItems2.append(childItems21);

        QStandardItem *childItems22 = new QStandardItem(str_dataset);
        childItems2.append(childItems22);

        items4.at(0)->appendRow(childItems2);

        pos += iTemp;
    }
    else
    {
        pos -= 1;
    }
    //=====================================================
    pos += 1;
    iTemp = 0, iLen_Temp = 0;

    if(pkt_data[pos] == 0x82)
    {
        QString str_smpcnt_data = "0x";
        int int_smpcnt = 0;

        pos += 1;
        iTemp = pkt_data[pos];

        for(j = 1; j <= iTemp; j++)
        {
            str_smpcnt_data += getHexFormat(pkt_data[pos + j]);
            // iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );
            int_smpcnt += (pkt_data[ pos + j ] << (8 * (iTemp - j)) );
        }

        pos += iTemp;

        QList<QStandardItem *> childItems3;

        QStandardItem *childItems30 = new QStandardItem(QString("SmpCnt"));
        childItems3.append(childItems30);

        QStandardItem *childItems31 = new QStandardItem(str_smpcnt_data);
        childItems3.append(childItems31);

        QStandardItem *childItems32 = new QStandardItem(QString::number(int_smpcnt));
        childItems3.append(childItems32);

        items4.at(0)->appendRow(childItems3);

        qDebug()<<"smpCnt"<<str_smpcnt_data<<int_smpcnt;
    }else
    {
            return false;
    }
//    //===============================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;

    QString str_cfgRev_data = "0x";
    int int_cfgRev = 0;

    if(pkt_data[pos] == 0x83)         // 配置版本
    {
        pos += 1;
        iLen_Temp = pkt_data[pos];
        for(j = 1; j <= iLen_Temp; j++)
        {
            str_cfgRev_data += getHexFormat(pkt_data[pos + j]);
            int_cfgRev += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
        }
        pos += iLen_Temp;

        QList<QStandardItem *> childItems4;

        QStandardItem *childItems40 = new QStandardItem(QString("配置版本"));
        childItems4.append(childItems40);

        QStandardItem *childItems41 = new QStandardItem(str_cfgRev_data);
        childItems4.append(childItems41);

        QStandardItem *childItems42 = new QStandardItem(QString::number(int_cfgRev));
        childItems4.append(childItems42);

        items4.at(0)->appendRow(childItems4);

        qDebug()<<"cfgRev"<<str_cfgRev_data<<int_cfgRev;

    }else
        return false;
//    sPartName = "\n配置版本：" + QString::number(iTemp,16);
//    m_sAnalyseResult +=  sPartName;
    //===============================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;
    if(pkt_data[pos] == 0x84)         //刷新时间refrTm
    {
        pos += 1;
        iTemp = pkt_data[pos];
        int m_iRef_Length=0;
        if(iTemp > 0x80)
        {
            iLen_Temp = iTemp - 0x80;
            for(j = 1; j <= iLen_Temp; j++)
                    m_iRef_Length += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
        }else
        {
            m_iRef_Length = iTemp;
        }
        pos += m_iRef_Length;
    }
    else
        pos -= 1;
    //==================================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;

    if(pkt_data[pos] == 0x85)             // 采样同步
    {
        QString str_sync_data = "0x";
        QString str_sync = "";

        pos += 2;

        str_sync_data += getHexFormat(pkt_data[pos]);

        if( pkt_data[pos] == 0)
                str_sync = "未同步";
        else
                str_sync = "已同步";

        QList<QStandardItem *> childItems5;

        QStandardItem *childItems50 = new QStandardItem(QString("同步标志"));
        childItems5.append(childItems50);

        QStandardItem *childItems51 = new QStandardItem(str_sync_data);
        childItems5.append(childItems51);

        QStandardItem *childItems52 = new QStandardItem(str_sync);
        childItems5.append(childItems52);

        items4.at(0)->appendRow(childItems5);

        qDebug()<<"SyncFlag"<<str_sync_data<<str_sync;
    }else
            return false;
//    m_sAnalyseResult +=  sPartName;
    //===============================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;
    if(pkt_data[pos] == 0x86)         //采样速率smpRate
    {
        is_92_le = false;

        QString str_smpRate_data = "0x";
        QString str_smpRate = "";

        pos += 1;

        iTemp = pkt_data[pos];

        if(iTemp > 0x80)
        {
            iLen_Temp = iTemp - 0x80;
            iTemp = 0;
            for(j = 1; j <= iLen_Temp; j++)
                    iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
            iTemp += iLen_Temp;
        }

        for(j = 1; j <= iTemp; j++)
            str_smpRate_data += getHexFormat(pkt_data[pos + j]);

        pos += iTemp;

        QList<QStandardItem *> childItems6;

        QStandardItem *childItems60 = new QStandardItem(QString("采样频率"));
        childItems6.append(childItems60);

        QStandardItem *childItems61 = new QStandardItem(str_smpRate_data);
        childItems6.append(childItems61);

        QStandardItem *childItems62 = new QStandardItem(str_smpRate);
        childItems6.append(childItems62);

        items4.at(0)->appendRow(childItems6);
    }
    else
        pos -= 1;
    //===============================================================
    iTemp = 0, iLen_Temp = 0;
    pos += 1;

    if(pkt_data[pos] == 0x87)             // 数据序列
    {
        int no_of_channel = 0;

        pos += 1;
        iTemp = pkt_data[pos];
        if(iTemp > 0x80)
        {
            iLen_Temp = iTemp - 0x80;
            iTemp = 0;
            for(j = 1; j <= iLen_Temp; j++)
                    iTemp += (pkt_data[pos + j] << (8 * (iLen_Temp - j)));
            pos = pos + iLen_Temp;
        }

        no_of_channel = iTemp / 8;

        QList<QStandardItem *> childItems7;

        QStandardItem *childItems70 = new QStandardItem(QString("通道总数"));
        childItems7.append(childItems70);

        QStandardItem *childItems71 = new QStandardItem("");
        childItems7.append(childItems71);

        QStandardItem *childItems72 = new QStandardItem(QString::number(no_of_channel)+" 个");
        childItems7.append(childItems72);

        items4.at(0)->appendRow(childItems7);

    }else
        return false;

    QList<QStandardItem *> items5;

    QStandardItem *item50 = new QStandardItem(QString("协议类型"));
    items5.append(item50);
    QStandardItem *item51;
    if(is_92_le)
        item51 = new QStandardItem(QString("9-2 LE"));
    else
        item51 = new QStandardItem(QString("9-2"));
    items5.append(item51);

    show_protocol->insertRow(0, items5);

    return true;
//    sPartName = "  数据序列：长度" + QString::number(iTemp,16);
//    m_iTongDaoCount = iTemp / m_iTongDao_Length;
//    m_iTongDatCountReal = m_iTongDaoCount;
////        if(m_iTongDaoCount > 12) m_iTongDaoCount = 12;
//    m_iFirstData_Start = iLocation + 1;			// 数据起始位置
//    m_sAnalyseResult +=  sPartName;
//    return true;
}


// 捕获下一个包
bool CapPacket::myLubo(void)
{
    if(m_bStopCap) return true;

    struct pcap_pkthdr *header;	// 数据包头
    const u_char *pkt_data;		// 数据包
    int iData_Start;			// 数据位起始位
    int iSmpCnt_Start;			// SmpCount起始位
    int iSmpCnt;				// SmpCount值
    int iShuZiLiang;			// 数字量
    int res;
    if (m_iSmpRate<=0) m_iSmpRate=CYPL/50;

    if((res = pcap_next_ex(m_fp, &header, &pkt_data)) > 0)
    {                               // 符合规约标准
        if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
        {
            //qDebug()<<"myLubo, new pcaket"<<m_iZhouQi<<m_iTestedPoints;

            for(int j = 0; j < m_iASDU_Cnt; j++)
            {
                if(m_bStopCap) return true;		// 外部阻止接口

                int i;

                iSmpCnt = 0;                // 获取SmpCount值
                iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(i = 0; i < m_iSmpCnt_Length; i++)
                    iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );

                for (int k = 0; k < 12; k++)
                {
                    bool isNotEmpty = true;

                    int kk = k;

                    if(k > m_iTongDaoCount - 1)
                    {
                        kk = m_iTongDaoCount;
                        isNotEmpty = false;
                    }

                    iShuZiLiang = 0;
                    iData_Start = m_iFirstData_Start + m_iTongDao_Length * kk;

                    for(i = 0; i < m_iData_Length; i++)
                        iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                    if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                    iShuZiLiang += 0xFFFF0000;

                    int iTemp = std::fabs(iShuZiLiang);
                    if(iTemp > m_iShuZiLiangMax_Temp)
                        m_iShuZiLiangMax_Temp = iTemp;

                    if (isNotEmpty)
                    {
                        m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                    }
                    else
                    {
                        m_PointArray[k][m_iTestedPoints] = 0.000001;
                    }
                }

                if(m_iTestedPoints < m_iZhouQi * m_iSmpRate - 1)
                {
                    luboIsEnd = false;
                    m_iTestedPoints++;

                    pcap_dump((unsigned char*)dumpfile,header,pkt_data); //写入
                }
                else if(!luboIsEnd)
                {
                    luboIsEnd = true;
                    m_bStopCap = true;

                    qDebug()<<"pcap_dump is done!"<<QString::number( m_iShuZiLiangMax_Temp, 'f',2);

                    pcap_dump((unsigned char*)dumpfile, header, pkt_data); //写入
                    pcap_dump_close(dumpfile);   //关闭

                    m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                    m_iShuZiLiangMax_Temp = 0;

                    sigCyOver();
                }
            }
        }
    }
}

// 捕获下一个包
bool CapPacket::showAll(void)
{
    if(m_bStopCap) return true;

    struct pcap_pkthdr *header;	// 数据包头
    const u_char *pkt_data;		// 数据包
    int iData_Start;			// 数据位起始位
    int iSmpCnt_Start;			// SmpCount起始位
    int iSmpCnt;				// SmpCount值
    int iShuZiLiang;			// 数字量
    int res;
    if (m_iSmpRate<=0) m_iSmpRate=CYPL/50;

    if((res = pcap_next_ex(m_fp, &header, &pkt_data)) > 0)
    {                               // 符合规约标准
        if(pkt_data[m_iAPDU_Start - 10] == 0x88 && pkt_data[m_iAPDU_Start - 9] == 0xba)
        {
            //qDebug()<<"myLubo, new pcaket"<<m_iZhouQi<<m_iTestedPoints;

            for(int j = 0; j < m_iASDU_Cnt; j++)
            {
                if(m_bStopCap) return true;		// 外部阻止接口

                int i;

                iSmpCnt = 0;                // 获取SmpCount值
                iSmpCnt_Start = m_iFirstSmpCnt_Start + j * (m_iASDU_Length);

                for(i = 0; i < m_iSmpCnt_Length; i++)
                    iSmpCnt += (pkt_data[iSmpCnt_Start + i] << (8 * (m_iSmpCnt_Length - i -1)) );

                int nBand = ( m_iTongDao / 12 ) * 12;

                for (int k = 0; k < 12; k++)
                {
                    bool isNotEmpty = true;

                    int kk = k + nBand;

                    if(kk > m_iTongDaoCount - 1)
                    {
                        kk = m_iTongDaoCount;
                        isNotEmpty = false;
                    }

                    iShuZiLiang = 0;
                    iData_Start = m_iFirstData_Start + m_iTongDao_Length * kk;

                    for(i = 0; i < m_iData_Length; i++)
                        iShuZiLiang += (pkt_data[iData_Start + i] << (8 * (m_iData_Length - i - 1)) );
                    if(m_sGuiYueType == GuiYue9_1 && iShuZiLiang >= 0x8000 && iShuZiLiang <= 0xFFFF)
                    iShuZiLiang += 0xFFFF0000;

                    int iTemp = std::fabs(iShuZiLiang);
                    if(iTemp > m_iShuZiLiangMax_Temp)
                        m_iShuZiLiangMax_Temp = iTemp;

                    if (isNotEmpty)
                    {
                        m_PointArray[k][m_iTestedPoints] = iShuZiLiang;// 存储绘图所需数字量数组
                    }
                    else
                    {
                        m_PointArray[k][m_iTestedPoints] = 0.000001;
                    }
                }

                if(m_iTestedPoints < m_iZhouQi * m_iSmpRate - 1)
                {
                    m_iTestedPoints++;
                }
                else if( iSmpCnt == 0 )
                {
                    m_iTestedPoints = 0;
                    m_iShuZiLiangMax = m_iShuZiLiangMax_Temp;
                    m_iShuZiLiangMax_Temp = 0;

                    memcpy(m_tempArray, m_PointArray, sizeof(m_tempArray));

                    sigCyOver();
                }
            }
        }
    }
}
